package com.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.util.DateUtils;
import com.util.RandomPasswdCreater;

/**
 * 
 * <p>功能描述:文件上传Action基类</p>
 * @author  <a href="mailto: zhuyoulong@gtss.com.cn">zhuyoulong</a>
 * @create_date 2008-10-23
 * @version $ Revision: 1.0
 */
@SuppressWarnings("serial")
public abstract class FileUploadAction extends BaseAction {

	private static final int BUFFER_SIZE = 16 * 1024;
	/**
	 * 文件基本目录，配置文件读入，绝对路径
	 */
	public  String WEB_ROOT =  getMyConfigPropertyValue("webroot");
	/**
	 * 所有用户上传基本目录，相对路径,一般用这个作为默认路径
	 */
	public static final String DATA_MANAGE_UPLOAD = "/UserFiles/picture";
	/**
	 * 所有用户上传基本目录，相对路径
	 */
	public static final String DEFAULT_UPLOAD_PATH = "/UserFiles/file";
	

    /**
     * 单文件上传,在页面中要定义一个myFile的文件域
     */
	File myFile;
	/**
	 * 文件类型
	 */
	String contentType;
	/**
	 * 文件名
	 */	
	String fileName;
	/**
	 * 默认文件上传路径
	 */
	public String filepath = DATA_MANAGE_UPLOAD;
	public String src = "";//文件路径
	/**
	 * 自动生成文件名
	 */
	public String autofileName = DateUtils.getDateTimeString2(DateUtils.getCurrentDate());
	public boolean IS_SUPPORT_FILE = false;
	private String[] only_pic = new String[]{"gif","jpg","jpeg","png"};
	private String[] pic_or_flash = new String[]{"gif","jpg","jpeg","png","swf"};
	
	//上传任意多个文件
//	private File[] upload;
////	 用String数组来封装多个上传文件名    
//    private String[] uploadFileName;    
//    // 用String数组来封装多个上传文件类型    
//    private String[] uploadContentType;
	
//	public File[] getUpload() {
//		return upload;
//	}
//
//	public void setUpload(File[] upload) {
//		this.upload = upload;
//	}
//
//	public String[] getUploadContentType() {
//		return uploadContentType;
//	}
//
//	public void setUploadContentType(String[] uploadContentType) {
//		this.uploadContentType = uploadContentType;
//	}
//
//	public String[] getUploadFileName() {
//		return uploadFileName;
//	}
//
//	public void setUploadFileName(String[] uploadFileName) {
//		this.uploadFileName = uploadFileName;
//	}
	
	//end 上传任意多个文件
	
	

	public void setMyFileContentType(String contentType) {
		this.contentType = contentType;
	}
	public void setMyFileFileName(String fileName) {
		this.fileName = fileName;
	}
	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}
	public String getMyFileFileName(){
		return fileName;
	}
	public String getMyFileContentType(){
		return contentType;
	}
	/**
	 * 获得文件全名
	 * @param fileName 文件名
	 * @return 
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public String getFullFileName(String fileName){
		Date photodate = new Date();
		String extention = this.getExtention(fileName);
		return photodate.getTime() + RandomPasswdCreater.getGuid(6) + "."+ extention;
	}
	/**
	 * 上传多个文件并且返回多个文件路径数组
	 * @return
	 * @throws Exception
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
//	public List uploadFiles() throws Exception {
//		List fileNameList = new ArrayList();
//		String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
////		 处理每个要上传的文件
//        for (int i = 0; i < upload.length; i++) {
//            // 根据服务器的文件保存地址和原文件名创建目录文件全路径        	
//            String dstPath = DEFAULT_UPLOAD_PATH+ "/"+subfilename+"/" + getFullFileName(this.getUploadFileName()[i]);
//            File dstFile = new File(dstPath);
//            this.uploadFile(DEFAULT_UPLOAD_PATH+ "/"+subfilename+"/", getFullFileName(fileName), upload[i]);
////            this.copy(upload[i], dstFile);
//            fileNameList.add(dstPath);
//        }
//		return fileNameList;
//	}
	/**
	 * 通过文件获得文件的扩展名
	 */
	public static String getExtention(String fileName)  {
        int pos = fileName.lastIndexOf(".");
        return fileName.substring(pos+1);
    }
	
	/**
	 * 返回用户上传相对目录，如/UserFiles/datamanage/0/0/8
	 * @param userId
	 * @return
	 */
	public static String genUserDir(Long userId){
		Long userId2 = userId/1000;
		Long userId3 = userId2/1000;
		userId2 = userId2 - userId3*1000;
		String userPath = "/"+userId3+"/"+userId2+"/"+userId;
		return DATA_MANAGE_UPLOAD + userPath;
	}
	/**
	 * 拷贝文件，即传文件
	 * @param src
	 * @param dst
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				int length = in.read(buffer);
				while ( length> 0) {
					byte[] temp = new byte[length];
					for(int i=0;i<length;i++){
						temp[i]=buffer[i];
					}
					out.write(temp);
					length = in.read(buffer);
				}
			} finally {
				if (null != in) {					
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected String validataAdvertiseUpload(){
		if (this.getMyFileFileName() != null
				&& this.getMyFileFileName().length() > 0) {
//			扩展名

			String extention = this
			.getExtention(this.getMyFileFileName());
			if (extention != null) {
				if (extention.equalsIgnoreCase("gif") || extention.equalsIgnoreCase("jpg") || extention.equalsIgnoreCase("png") || extention.equalsIgnoreCase("jpeg") || extention.equalsIgnoreCase("swf")){
					String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
					Date photodate = new Date();
					String filename = photodate.getTime()
					+ RandomPasswdCreater.getGuid(6) + "."
					+ extention;
					this.uploadFile(filepath+"/"+subfilename, filename);
					
					src = filepath + "/"+subfilename+"/" + filename;
				}
			}
		}
		if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
		return src;
	}
	
	/**
	 * 
	 * <p>功能描述：验证图片上传是否合法,前台页面脚本判断通过的前提下，这里也需要后台验证，增加安全性</p>
	 * @return
	 * @author:Administrator
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	protected String validataUpload(){
		if (this.getMyFileFileName() != null
				&& this.getMyFileFileName().length() > 0) {
//			扩展名
			
			String extention = this
			.getExtention(this.getMyFileFileName());
			if (extention != null) {
				if (extention.equalsIgnoreCase("gif") || extention.equalsIgnoreCase("jpg") || extention.equalsIgnoreCase("jpeg") || extention.equalsIgnoreCase("png")  || extention.equalsIgnoreCase("doc") || extention.equalsIgnoreCase("xls")){
					String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
					Date photodate = new Date();
					String filename = photodate.getTime()
					+ RandomPasswdCreater.getGuid(6) + "."
					+ extention;
					this.uploadFile(filepath+"/"+subfilename, filename);
					
					src = filepath + "/"+subfilename+"/" + filename;
				}
			}
		}
		if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
		return src;
	}
	
	
	protected String validataPicOrFlashUpload(){
		if (this.getMyFileFileName() != null
				&& this.getMyFileFileName().length() > 0) {
//			扩展名

			String extention = this
			.getExtention(this.getMyFileFileName());
			if (extention != null) {
				if (extention.equalsIgnoreCase("gif") || extention.equalsIgnoreCase("jpg") || extention.equalsIgnoreCase("jpeg") || extention.equalsIgnoreCase("png") || extention.equalsIgnoreCase("swf")){
					String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
					Date photodate = new Date();
					String filename = photodate.getTime()
					+ RandomPasswdCreater.getGuid(6) + "."
					+ extention;
					this.uploadFile(filepath+"/"+subfilename, filename);
					
					src = filepath + "/"+subfilename+"/" + filename;
				}
			}
		}
		if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
		return src;
	}
	
	protected String validataSmallUpload(File file,String filename){
		
		if (this.getSmallPicFileName() != null
				&& this.getSmallPicFileName().length() > 0) {
//			扩展名

			String extention = this
			.getExtention(this.getSmallPicFileName());
			if (extention != null) {
				if (extention.equalsIgnoreCase("gif") || extention.equalsIgnoreCase("jpg")  || extention.equalsIgnoreCase("jpeg") || extention.equalsIgnoreCase("png")){
					String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
					filename+="."+ extention;
					this.uploadFile(filepath+"/"+subfilename+"/small", filename,file);
					
					src = filepath + "/"+subfilename+"/small/" + filename;
				}
			}
		}
		if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
		return src;
	}
	public String getMyFileName(String filename){
		return "get"+filename+"FileName()";
	}
	
	protected String validataMiddleUpload(File file,String filename){
		if (this.getMiddlePicFileName() != null
				&& this.getMiddlePicFileName().length() > 0) {
//			扩展名

			String extention = this
			.getExtention(this.getMiddlePicFileName());
			if (extention != null) {
				if (extention.equalsIgnoreCase("gif") || extention.equalsIgnoreCase("jpg")  || extention.equalsIgnoreCase("jpeg") || extention.equalsIgnoreCase("png")){
					String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
					filename+="."+ extention;
					this.uploadFile(filepath+"/"+subfilename+"/middle", filename,file);
					
					src = filepath + "/"+subfilename+"/middle/" + filename;
				}
			}
		}
		if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
		return src;
	}
	
	protected String validataBigUpload(File file,String filename){
		if (this.getBigPicFileName() != null
				&& this.getBigPicFileName().length() > 0) {
//			扩展名

			String extention = this
			.getExtention(this.getBigPicFileName());
			if (extention != null) {
				if (extention.equalsIgnoreCase("gif") || extention.equalsIgnoreCase("jpg")  || extention.equalsIgnoreCase("jpeg") || extention.equalsIgnoreCase("png")){
					String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
					filename+="."+ extention;
					this.uploadFile(filepath+"/"+subfilename+"/big", filename,file);
					
					src = filepath + "/"+subfilename+"/big/" + filename;
				}
			}
		}
		if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
		return src;
	}
	
	protected String validataListUpload(File file,String filename){
		if (this.getListPicFileName() != null
				&& this.getListPicFileName().length() > 0) {
//			扩展名

			String extention = this
			.getExtention(this.getListPicFileName());
			if (extention != null) {
				if (extention.equalsIgnoreCase("gif") || extention.equalsIgnoreCase("jpg") || extention.equalsIgnoreCase("jpeg") || extention.equalsIgnoreCase("png")){
					String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
					filename+="."+ extention;
					this.uploadFile(filepath+"/"+subfilename+"/list", filename,file);
					
					src = filepath + "/"+subfilename+"/list/" + filename;
				}
			}
		}
		if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
		return src;
	}
	
	protected String validataAdvertisePicUpload(File file,String filename){
		if(this.getAdvertisePicFileName()!=null && this.getAdvertisePicFileName().length()>0){
			String extention = this.getExtention(this.getAdvertisePicFileName());
			if(extention !=null){
				if(extention.equalsIgnoreCase("gif")||extention.equalsIgnoreCase("jpg") || extention.equalsIgnoreCase("jpeg") ||extention.equalsIgnoreCase("png")){
					String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
					filename+="."+extention;
					this.uploadFile(filepath+"/"+subfilename,filename,file);
					src = filepath +"/" +subfilename+"/"+filename;
				}
			}
		}
		if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
		 return src;
	}

	/**
	 * <p>功能描述：验证并上传图片文件,默认传myFile文件</p>
	 * @param formFilename
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	protected String validateAndUploadFile(String formFilename){
    	if (formFilename != null
				&& formFilename.trim().length() > 0) {
    		String extention = this.getExtention(formFilename);
    		if (extention != null) {
				if (extention.equalsIgnoreCase("gif") || extention.equalsIgnoreCase("jpg") || extention.equalsIgnoreCase("jpeg") || extention.equalsIgnoreCase("png") || extention.equalsIgnoreCase("swf")){
					String subfilename = DateUtils.getDateMonthString(DateUtils.getCurrentDate());
					Date photodate = new Date();
					String filename = photodate.getTime()
					+ RandomPasswdCreater.getGuid(6) + "."
					+ extention;
					this.uploadFile(filepath+"/"+subfilename, filename);
					
					src = filepath + "/"+subfilename+"/" + filename;
				}
			}
    	}
    	if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
    	return src;
    }
	/**
	 * 文件名随便在action中设置
	 * @param formFilename form表单中的文件名
	 * @param forder 制定存放目录
	 * @param file 文件
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	protected String validateAndUploadFile(String formFilename,String forder,File file){
    	if (formFilename != null
				&& formFilename.trim().length() > 0) {
    		String extention = this.getExtention(formFilename);
    		if (extention != null) {
				if (extention.equalsIgnoreCase("gif") || extention.equalsIgnoreCase("jpg") || extention.equalsIgnoreCase("jpeg") || extention.equalsIgnoreCase("png") || extention.equalsIgnoreCase("swf")){
					Date photodate = new Date();
					String filename = photodate.getTime()
					+ RandomPasswdCreater.getGuid(6) + "."
					+ extention;
					this.uploadFile(filepath+"/"+forder, filename,file);
					
					src = filepath + "/"+forder+"/" + filename;
				}
			}
    	}
    	if(src!=null || !src.equals("")){
			IS_SUPPORT_FILE = true;
		}
    	return src;
    }
	
	
	/**
	 * 上传文件
	 * @param strFilePath 相对url目录，如/UserFiles/picture
	 * @param fileName 文件名，如bbc.jpg
	 */
	public void uploadFile(String strFilePath, String fileName){
		//创建上传文件路径实例
		File dir = new File(WEB_ROOT + strFilePath);
		if(!dir.exists()){
			dir.mkdirs();
		}
        File file = new File(WEB_ROOT + strFilePath + "/" + fileName);
        copy(myFile,file);
	}
	/**
	 * 上传文件
	 * @param strFilePath
	 * @param fileName
	 * @param sourceFile
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void uploadFile(String strFilePath, String fileName,File sourceFile){
		//创建上传文件路径实例
		File dir = new File(WEB_ROOT + strFilePath);
		if(!dir.exists()){
			dir.mkdirs();
		}
        File file = new File(WEB_ROOT + strFilePath + "/" + fileName);
        copy(sourceFile,file);
	}
	
	/**
	 * <p>功能描述：删除文件</p>
	 * @param delDir 要删除的文件路径,""默认网站根目录
	 * @param delFile 要删除的文件名
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void deleteFile(String delDir,String delFile){
		File deleteFile = new File(WEB_ROOT + delDir + "/" + delFile);
		File deleteDir = new File(WEB_ROOT + delDir);
		if(deleteFile.exists()){
			deleteFile.delete();
		}
		if(deleteDir.exists()){
			deleteDir.delete();
		}
	}
	
	/**
	 * <p>功能描述：删除多个文件,批量删除</p>
	 * @param picList 图片路径数组
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void deleteMultiFile(List picList){
		if( picList != null && picList.size() > 0 ){
			int SIZE = picList.size();
			for(int i=0;i<SIZE;i++){
				String fileUrl = picList.get(i).toString();
				File deleteFile = new File(WEB_ROOT + "/" + fileUrl);
				if(deleteFile.exists()){
					deleteFile.delete();
				}
			}
		}
	}
	/**
	 * 判断目录是否存在
	 * @param fdir
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public boolean exists(String fdir){
		File f = new File(ServletActionContext.getServletContext().getRealPath(fdir ));
		f = new File(f.getPath().replaceFirst("WebRoot",WEB_ROOT));
		return f.exists();
	}
	
	public int fileSize(){
		int i=0;
		myFile.length();
		return i;
	}
	/**
	 * 根据年月日 获得文件路径
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public String getFilepathForYearMonthDay() {
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy/MM/dd");
		String yyyyMMdd = sdf.format(new Date());
		return filepath + "/" + yyyyMMdd;
	}
	/**
	 * <p>功能描述：生成文件名</p>
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public String createFileName(){
		String filename = DateUtils.getDateTimeString2(DateUtils.getCurrentDate());
		return filename;
	}
	
	public String getFilepath() {
		return filepath;
	}
	public void setFilepath(String filepath) {
		this.filepath = filepath;
	}
	public String getSrc() {
		return src;
	}
	public void setSrc(String src) {
		this.src = src;
	}
	
	
	/**
	 * 小图片

	 */
	protected File smallPic;
	/**
	 * 产品详细页面中间图片
	 */
	protected File middlePic;
	/**
	 * 大图片

	 */
	protected File bigPic;
	/**
	 * 分类页面图片
	 */
	protected File listPic;
	
	/**
	 * 广告图片
	 */
	protected File advertisePic;
	/**
	 * 小图片名称

	 */
	protected String fileName1;
    /**
     * 中间图片名字
     */
	protected String fileName3;
    /**
     * 大图片名称

     */
	protected String fileName2;
    /**
     * 列表图片名称
     */
    private String fileName4;
    /**
     * 广告图片名称
     */
    private String fileName5;

	public String getSmallPicContentType(){
		return contentType;
	}
    
	public void setSmallPicFileName(String fileName) {
		this.fileName1 = fileName;
	}
	
	public String getSmallPicFileName(){
		return fileName1;
	}
	public void setMiddlePicFileName(String fileName) {
		this.fileName3 = fileName;
	}
	
	public String getMiddlePicFileName(){
		return fileName3;
	}
	public void setBigPicFileName(String fileName) {
		this.fileName2 = fileName;
	}
	
	public String getBigPicFileName(){
		return fileName2;
	}

    public File getBigPic() {
		return bigPic;
	}

	public void setBigPic(File bigPic) {
		this.bigPic = bigPic;
	}

	public File getSmallPic() {
		return smallPic;
	}

	public void setSmallPic(File smallPic) {
		this.smallPic = smallPic;
	}

	public File getMiddlePic() {
		return middlePic;
	}

	public void setMiddlePic(File middlePic) {
		this.middlePic = middlePic;
	}

	public File getListPic() {
		return listPic;
	}

	public void setListPic(File listPic) {
		this.listPic = listPic;
	}
	
	public File getAdvertisePic() {
		return advertisePic;
	}
	public void setAdvertisePic(File advertisePic) {
		this.advertisePic = advertisePic;
	}
	
	public String getListPicFileName(){
		return fileName4;
	}
	public void setListPicFileName(String fileName) {
		this.fileName4 = fileName;
	}
	
	public String getAdvertisePicFileName(){
		return fileName5;
	}
	
	public void setAdvertisePicFileName(String fileName){
		this.fileName5 = fileName;
	}

    /**
     * -------------------start 定义批量上传文件------------------------
     * 页面中的写法：<input type="file" name="upload">
     * action中获得，写法如下：
     * for (int i = 0; i < uploads.length; i++) {
     *          //如果从页面上获得的附件路径
                String filename = this.getUploadFileName()[i];
                filename = System.currentTimeMillis() + FileUtils.getExtension(filename,"");
                this.uploadFile(DEFAULT_UPLOAD_PATH + "/", filename, uploads[i]);
     * ｝
     */
    private File[] uploads;
    private String[] uploadFileNames;
    private String[] uploadContentTypes;

    public File[] getUpload() {
        return uploads;
    }
    public void setUpload(File[] upload) {
        this.uploads = upload;
    }
    public String[] getUploadFileName() {
        return uploadFileNames;
    }
    public void setUploadFileName(String[] uploadFileName) {
        this.uploadFileNames = uploadFileName;
    }
    public String[] getUploadContentType() {
        return uploadContentTypes;
    }
    public void setUploadContentType(String[] uploadContentType) {
        this.uploadContentTypes = uploadContentType;
    }
    /**
     * ---------------------end 定义批量上传文件-----------------------
     */
}
